using System.Runtime.InteropServices;

namespace torch.ui;

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public class ScreenCapture
{
    [DllImport("user32.dll")]
    private static extern int GetSystemMetrics(int nIndex);

    // GetSystemMetrics 的常用索引
    private const int SM_CXSCREEN = 0; // 主屏幕宽度
    private const int SM_CYSCREEN = 1; // 主屏幕高度

    private string _saveDir;
    
    public ScreenCapture(string saveDir)
    {
        _saveDir = saveDir;
        if (!Directory.Exists(saveDir))
        {
            Directory.CreateDirectory(saveDir);
        }
    }

    public string? CaptureFullScreen()
    {
        try
        {
            int screenWidth = GetSystemMetrics(SM_CXSCREEN);
            int screenHeight = GetSystemMetrics(SM_CYSCREEN);
            Rectangle bounds = new Rectangle(
                0,
                0,
                screenWidth,
                screenHeight
            );

            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(bounds.Left, bounds.Top, 0, 0, bounds.Size, CopyPixelOperation.SourceCopy);
                }

                string fileName = $"screenshot_{DateTime.Now:yyyyMMddHHmmss}.jpg";
                string? filePath = Path.Combine(_saveDir, fileName);

                bitmap.Save(filePath, ImageFormat.Png);
                return filePath;
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}